﻿/*
   　　　　　　　　　　　　　　│
*└──────────────────────────────────┘
*/

using System;
using System.Data;
using System.Text;
using System.Web;
using XHD.Common;
using XHD.Controller;

namespace XHD.Server
{
    public class Basic_Corral
    {
        public static BLL.Basic_corral category = new BLL.Basic_corral();
        public static Model.Basic_corral model = new Model.Basic_corral();

        public HttpContext Context;
        public string emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;
        

        public Basic_Corral()
        {
        }

        public Basic_Corral(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            employee = userinfo.GetCurrentEmpInfo(context);

            emp_id = employee.id;
            emp_name = PageValidate.InputText(employee.name, 50);
            uid = PageValidate.InputText(employee.uid, 50);
            
        }

        public string save()
        {
            model.corralName = PageValidate.InputText(request["T_corralName"], 50);
            model.remarks = PageValidate.InputText(request["T_remarks"], 250);
            model.area = decimal.Parse(PageValidate.InputText(request["T_area"], 250));
            model.def1 = PageValidate.InputText(request["T_category_icon"], 250);
            model.dornId = PageValidate.InputText(request["pid"], 250);
            string id = PageValidate.InputText(request["id"], 50);
            string sql = "SELECT * FROM  dbo.Basic_corral WHERE corralName='" + model.corralName + "' AND dornId='" + model.dornId + "'";
            

                if (PageValidate.checkID(id))
                {
                sql += " AND id!='"+id+"'";
                DataSet ds = DBUtility.DbHelperSQL.Query(sql);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    return XhdResult.Error("【" + model.corralName + "】名称已存在！").ToString();
                }
                else
                {
                    model.id = id;

                    category.Update(model);

                    string UserID = emp_id;
                    string UserName = emp_name;
                    string IPStreet = request.UserHostAddress;
                    string EventTitle = model.corralName;
                    string EventType = "药品周期修改";
                    string EventID = model.id;
                    string Log_Content = null;


                    if (!string.IsNullOrEmpty(Log_Content))
                        Syslog.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, Log_Content);

                }

                }

                else
                {

                DataSet ds = DBUtility.DbHelperSQL.Query(sql);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    return XhdResult.Error("【" + model.corralName + "】名称已存在！").ToString();
                }
                else
                {
                    model.id = Guid.NewGuid().ToString();
                    model.create_id = emp_name;
                    model.create_time = DateTime.Now;
                    category.Add(model);
                }
                }
                return XhdResult.Success().ToString();
            
        }


        public string saveLog()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(" INSERT INTO dbo.Basic_corral_check_log  ");
            sb.AppendLine(" (  ");
            sb.AppendLine("     id,  ");
            sb.AppendLine("     corralId,  ");
            sb.AppendLine("     dornId,  ");
            sb.AppendLine("     temperature,  ");
            sb.AppendLine("     humidity,  ");
            sb.AppendLine("     createPerson,  ");
            sb.AppendLine("     monitorPerson,  ");
            sb.AppendLine("     createTime  ");
            sb.AppendLine(" )  ");
            sb.AppendLine(" VALUES  ");
            sb.AppendLine(" (   '"+ Guid.NewGuid().ToString()+"',       -- id - varchar(50)  ");
            sb.AppendLine("     '"+ PageValidate.InputText(request["corralId"], 50) + "',       -- corralId - varchar(50)  ");
            sb.AppendLine("     '" + PageValidate.InputText(request["dornId"], 50) + "',       -- dornId - varchar(50)  ");
            sb.AppendLine("     " + PageValidate.InputText(request["T_temperature"], 50) + ",      -- temperature - float  ");
            sb.AppendLine("     " + PageValidate.InputText(request["T_humidity"], 50) + ",      -- humidity - float  ");
            sb.AppendLine("     '"+emp_name+"',       -- createPerson - varchar(50)  ");
            sb.AppendLine("     '" + PageValidate.InputText(request["T_monitorPerson"], 50) + "',       -- createPerson - varchar(50)  ");
            sb.AppendLine("     GETDATE() -- createTime - datetime  ");
            sb.AppendLine("     )  ");
            int i = DBUtility.DbHelperSQL.ExecuteSql(sb.ToString());
           if(i>0)
            return XhdResult.Success().ToString();
            else return XhdResult.Error("记录失败!").ToString();
        }
        

        public string grid()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " id";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = "asc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = $" 1=1 ";
            if (!string.IsNullOrEmpty(request["dornId"]))
                serchtxt += $" and dornId='{PageValidate.InputText(request["dornId"], 50)}'";

            //if (!string.IsNullOrEmpty(request["stext"]))
            //    serchtxt += $" and product_name like N'%{ PageValidate.InputText(request["stext"], 255) }%'";

            //权限
            DataSet ds = category.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);

            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);
            return (dt);

        }


        public string gridLog()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " id";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = "asc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = $" 1=1 ";
            if (!string.IsNullOrEmpty(request["cid"]))
                serchtxt += $" and corralId='{PageValidate.InputText(request["cid"], 50)}'";
            if (!string.IsNullOrEmpty(request["bid"]))
                serchtxt += $" and dornId='{PageValidate.InputText(request["bid"], 50)}'";

            //if (!string.IsNullOrEmpty(request["stext"]))
            //    serchtxt += $" and product_name like N'%{ PageValidate.InputText(request["stext"], 255) }%'";

            //权限

            DataSet ds = category.GetListLog(PageSize, PageIndex, serchtxt, sorttext, out Total);

            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);
            return (dt);

        }

        public string gridHealth()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " id";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = "asc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = $" 1=1 ";
            if (!string.IsNullOrEmpty(request["dornId"]))
                serchtxt += $" and dornId='{PageValidate.InputText(request["dornId"], 50)}'";
            //if (!string.IsNullOrEmpty(request["dornId"]))
            //    serchtxt += $" and id='{PageValidate.InputText(request["dornId"], 50)}'";
            //if (!string.IsNullOrEmpty(request["stext"]))
            //    serchtxt += $" and product_name like N'%{ PageValidate.InputText(request["stext"], 255) }%'";

            //权限
            DataSet ds = category.GetListHealth(PageSize, PageIndex, serchtxt, sorttext, out Total);

            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);
            return (dt);

        }

        public string tree(string id    )
        {
            DataSet ds = category.GetList($"1=1 and dornId='"+id+"'");
            var str = new StringBuilder();
            str.Append("[");
            str.Append(GetTreeString(id, ds.Tables[0]));
            str.Replace(",", "", str.Length - 1, 1);
            str.Append("]");
            return str.ToString();
        }

        public string combo(string id)
        {
            DataSet ds = category.GetList($"1=1");
            var str = new StringBuilder();
            str.Append("[");
            //str.Append("{\"id\":\"root\",\"text\":\"无\",\"d_icon\":\"\"},");
            str.Append(GetTreeString(id, ds.Tables[0]));
            str.Replace(",", "", str.Length - 1, 1);
            str.Append("]");
            return str.ToString();
        }

        public string form(string id)
        {
            if (!PageValidate.checkID(id)) return "{}";
            id = PageValidate.InputText(id, 50);
            DataSet ds = category.GetList($" id='{id}' ");
            return DataToJson.DataToJSON(ds);

        }

        //del
        public string del(string id)
        {
            if (!PageValidate.checkID(id)) return "false";
            id = PageValidate.InputText(id, 50);
          

            bool isdel = category.Delete(id);
            if (!isdel) return XhdResult.Error("系统错误！").ToString();

            //日志
            string EventType = "畜栏删除";

            string UserID = emp_id;
            string UserName = emp_name;
            string IPStreet = request.UserHostAddress;
            string EventID = id;
            string EventTitle = "";

            Syslog.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, null);

            return XhdResult.Success().ToString();

        }


        private static string GetTreeString(string Id, DataTable table)
        {
            DataRow[] rows = table.Select($"dornId='{Id}'");

            if (rows.Length == 0) return string.Empty;
            ;
            var str = new StringBuilder();

            foreach (DataRow row in rows)
            {
                str.Append("{\"id\":\"" + (string)row["id"] + "\",\"text\":\"" + (string)row["corralName"] + "\",\"d_icon\":\"../../" + (string)row["def1"] + "\"");

                //if (GetTreeString((string)row["id"], table).Length > 0)
                //{
                //    str.Append(",\"children\":[");
                //    str.Append(GetTreeString((string)row["id"], table));
                //    str.Append("]},");
                //}
                //else
                {
                    str.Append("},");
                }
            }
            return str[str.Length - 1] == ',' ? str.ToString(0, str.Length - 1) : str.ToString();
        }
    }
}
